package com.fa4j.system.app.controller;

import com.fa4j.common.base.exception.CommonRequestError;
import com.fa4j.common.base.model.RemoveCmd;
import com.fa4j.common.web.annotation.ApiMethod;
import com.fa4j.common.web.model.AppType;
import com.fa4j.system.app.model.AppMenu;
import com.fa4j.system.app.model.AppMenuCreateCmd;
import com.fa4j.system.app.model.AppMenuModifyCmd;
import com.fa4j.system.app.repository.AppMenuRepository;
import com.fa4j.system.app.service.AppMenuService;
import com.fa4j.system.login.util.LoginUtil;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("system/app/menu")
@RequiredArgsConstructor
public class AppMenuController {

    private final AppMenuService appMenuService;
    private final AppMenuRepository appMenuRepository;

    @ApiMethod(name = "系统应用菜单-树查询", type = AppType.MANAGE)
    @GetMapping("tree")
    public List<AppMenu> queryTree(AppType appType) {
        return appMenuRepository.queryTree(appType, null, null);
    }

    @ApiMethod(name = "系统应用菜单-详情查询", type = AppType.MANAGE)
    @GetMapping("{id}")
    public AppMenu detail(@PathVariable Integer id) {
        return appMenuRepository.findById(id)
                .orElseThrow(() -> CommonRequestError.NOT_FOUND.build("系统应用菜单"));
    }

    @ApiMethod(name = "系统应用菜单-创建", type = AppType.MANAGE)
    @PostMapping
    public AppMenu create(@Valid @RequestBody AppMenuCreateCmd cmd) {
        return appMenuService.create(cmd);
    }

    @ApiMethod(name = "系统应用菜单-编辑", type = AppType.MANAGE)
    @PatchMapping
    public AppMenu modify(@Valid @RequestBody AppMenuModifyCmd cmd) {
        return appMenuService.modify(cmd);
    }

    @ApiMethod(name = "系统应用菜单-删除", type = AppType.MANAGE)
    @DeleteMapping("{id}")
    public AppMenu remove(@PathVariable Integer id) {
        return appMenuService.remove(RemoveCmd.of(id, LoginUtil.getAccountId()));
    }

}
